package com.tiantian.quanminxiu.presenter;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.shenglian.utils.utils.CommonUtils;
import com.tiantian.quanminxiu.api.AnchorService;
import com.tiantian.quanminxiu.utils.APPUtils;
import com.tiantian.quanminxiu.utils.ApplicationBase;
import com.tiantian.quanminxiu.utils.Constants;
import com.tiantian.quanminxiu.utils.UserData;
import com.tiantian.quanminxiu.view.LoadingPageView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;

/**
 * Created by admin on 2016/8/11.
 */
public class LoadingPagePresent implements Presenter<LoadingPageView> {

    private LoadingPageView loadingPageView;
    private String webVersion;
    private String webDownload;

    @Override
    public void attachView(LoadingPageView view) {
        this.loadingPageView = view;
    }

    @Override
    public void detachView() {
        loadingPageView = null;
    }


    public void initLoadingPage(){

        String strEquipment_Code = null;
        SharedPreferences preference = PreferenceManager.getDefaultSharedPreferences(loadingPageView.getContext());
        strEquipment_Code = preference.getString("identity", null);
        if (strEquipment_Code == null || strEquipment_Code.equalsIgnoreCase("")) {
            TelephonyManager mTelephonyManager = (TelephonyManager) loadingPageView.getContext().getSystemService(Context.TELEPHONY_SERVICE);
            try {
                strEquipment_Code = mTelephonyManager.getDeviceId() != null ? mTelephonyManager.getDeviceId() : Settings.Secure.getString(loadingPageView.getContext().getContentResolver(), Settings.Secure.ANDROID_ID);
            } catch (Exception e) {
                strEquipment_Code = "";
            }

            Pattern mPattern = Pattern.compile("^(\\d)\\1+$");
            Matcher matcher = mPattern.matcher(strEquipment_Code);
            if (strEquipment_Code.equalsIgnoreCase("") || matcher.find()) {
                // 如果取到的机器码为空或者不符合要求。不符合要求的判断：重复一个数字
                strEquipment_Code = java.util.UUID.randomUUID().toString();
            }
            preference.edit().putString("identity", strEquipment_Code).commit();
        }

        ApplicationBase app = ApplicationBase.get(loadingPageView.getContext());
        AnchorService service = app.getAnchorService();
        final String finalStrEquipment_Code = strEquipment_Code;
        service.response(strEquipment_Code, Constants.EQUIPMENT_TYPE, Constants.APP_TYPE)
            .flatMap(str -> {
                Log.i("main", "--pa:giftlist" + str.toString());
                UserData.Current.mid = str.optInt("mid");
                webVersion = str.optString("version");
                webDownload = str.optString("download");
                UserData.Current.sign = CommonUtils.MD5(finalStrEquipment_Code + "|" + str.optString("auth_c"));
                return service.giftlist(UserData.Current.mid, UserData.Current.sign, Constants.APP_TYPE);
            }).flatMap(str -> {
                Log.i("main", "--pa:open" + str.toString());
                JSONArray giftArray = str.optJSONArray("data");
                UserData.Current.GiftList = giftArray;
                UserData.Current.WeekStar = new JSONArray();
                for (int i = 0; i < giftArray.length(); i++) {
                    JSONObject object = giftArray.optJSONObject(i);
                    if (object.optBoolean("WeekStar")) {
                        UserData.Current.WeekStar.put(object);
                    }
                }
                Log.i("main", "--pa:open:" + UserData.Current.WeekStar.toString());
                return service.guardianlist(UserData.Current.mid, UserData.Current.sign, Constants.APP_TYPE);
            }).flatMap(str -> {
                Log.i("main", "--pa:guarduanlist"+str.toString());
                UserData.Current.GuardConfigList = str.optJSONArray("data");
                return service.open(UserData.Current.mid, Constants.APP_TYPE, UserData.Current.sign
                        , UserData.Current.Equipment_Name, UserData.Current.Screen_Width, UserData.Current.Screen_Height
                        , UserData.Current.OS_Version, UserData.Current.APP_Version, UserData.Current.APP_VersionCode
                        , 116.307629, 40.058359);
            }).flatMap(str -> {
                if (str.optJSONObject("data").optInt("User_ID") == -1) {//用户没有登录
                    return Observable.just(str);
                }
                UserData.Current.USERCOVER_URL = str.optJSONObject("data").optString("ImgUserCover");
                UserData.Current.USERAVATAR_URL = str.optJSONObject("data").optString("ImgUserAvatar");
                return service.user_userinfo_info(UserData.Current.mid, UserData.Current.sign, Constants.APP_TYPE);
            })
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(app.defaultSubscribeScheduler())
            .subscribe(str -> {
                Log.i("main", "--pa:" + str.toString());
                Log.i("main", "--download:" + ApplicationBase.downAppUrl);
                if (str.optJSONObject("data").optInt("User_ID") != -1) {//用户已经登录
                    JSONObject value = str.optJSONObject("data");
                    UserData.Base.NickName = value.optString("NickName");
                    UserData.Base.Phone = value.optString("Phone");
                    UserData.Base.User_ID = value.optInt("User_ID");
                    UserData.Base.Coin = value.optInt("Coin");
                    UserData.Base.Beans = value.optInt("Beans");
                    UserData.Base.Sex = value.optInt("Sex");
                    UserData.Base.Attention = value.optInt("Attention");
                    UserData.Base.Pomelo = value.optInt("Pomelo");
                    UserData.Base.Status = value.optInt("Status");
                    UserData.Base.Level = value.optInt("Level");
                    UserData.Base.Fans = value.optInt("Fans");
                    UserData.Base.Signature = value.optString("Signature");
                    UserData.Base.isAnchor = value.optInt("IsAnchor") == 1 ? true : false;
                    UserData.Base.IsAdmin = value.optInt("IsAdmin") == 1 ? true : false;
                }
                if (compareVersion(webVersion)) {
                    loadingPageView.ShowUpDateDialog(str.optJSONObject("data").optInt("User_ID"), ApplicationBase.downAppUrl);
                }else if(APPUtils.getFirstStart(loadingPageView.getContext())){
                    loadingPageView.initViewPager();
                } else if (str.optJSONObject("data").optInt("User_ID") != -1) {//用户已经登录
                    loadingPageView.JumpMain();
                } else {
                    loadingPageView.JumpLogin();
                }
            }, throwable -> {
                CommonUtils.showToask(loadingPageView.getContext(), throwable.getMessage());
            });
    }

    //region 比较版本号大小 compareVersion(String version)
    public boolean compareVersion(String version){
        String[] splitVersion = version.split("\\.");
        String[] curVersion = UserData.Current.APP_Version.split("\\.");
        for (int i=0;i<curVersion.length;i++){
            try {
                if(Integer.parseInt(curVersion[i])>Integer.parseInt(splitVersion[i])){
                    return false;
                }else if(Integer.parseInt(curVersion[i])<Integer.parseInt(splitVersion[i])){
                    return true;
                }
            }catch (Exception e){
                return false;
            }
        }
        return false;
    }
    //endregion

}
